//
//  NSDataAES.m
//  IPTV
//
//  Created by Echo on 14-4-17.
//  Copyright (c) 2014年 Echo. All rights reserved.
//

#import "NSDataAES.h"
#import <CommonCrypto/CommonCryptor.h> 

#define aes_key @"ay3$&dw*ndAD!9)<"
#define aes_iv @"7e3*WwI(@Dczxcue"

@implementation NSData (Encryption)
/*
 校验方式：CRC16-CCITT ,多项式采用 0x1021
 加密方式：AES/CBC/PKCS5Padding
 */
- (NSData *)AES256EncryptWithKey{//加密
    NSString *key = aes_key;
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    NSString *initIv = aes_iv;
    const void *iv = (const void *) [initIv UTF8String];
//    static Byte ivBuff[]   = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6};
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES,//  加密根据哪个标准（des，3des，aes。。。。）
                                          kCCOptionPKCS7Padding,//  选项分组密码算法(des:对每块分组加一次密  3DES：对每块分组加三个不同的密)
                                          keyPtr,//密钥    加密和解密的密钥必须一致
                                          kCCBlockSizeAES128,//   DES 密钥的大小（kCCKeySizeDES=8）
                                          iv,//  可选的初始矢量
                                          [self bytes],
                                          dataLength,
                                          buffer, bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    free(buffer);
    return nil;
}


- (NSData *)AES256DecryptWithKey{//解密
    NSString *key = aes_key;
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    NSString *initIv = aes_iv;
    const void *iv = (const void *) [initIv UTF8String];
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES,
                                          kCCOptionPKCS7Padding,
                                          keyPtr, kCCBlockSizeAES128,
                                          iv,
                                          [self bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }
    free(buffer);
    return nil;
}

@end
